package com.saclub.app.activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.offroader.core.OffRoaderFragmentActivity;
import com.offroader.core.SystemBarTintManager;
import com.offroader.utils.StringUtils;
import com.saclub.app.R;
import com.saclub.app.common.MyPageHelper;
import com.saclub.app.fragment.BaseProgressFragment;

public class MyToolBarActivity extends OffRoaderFragmentActivity implements OnClickListener {

	public final static String BUNDLE_KEY_NAME = "BUNDLE_KEY_NAME";
	public final static String BUNDLE_KEY_ARGS = "BUNDLE_KEY_ARGS";

	public static final String BUNDLE_KEY_TITLE = "display_title";

	protected WeakReference<Fragment> mFragment;
	protected String name;
	protected ActionBar actionBar;
	protected Toolbar mToolbar;
	protected TextView leftTitleText;
	protected TextView titleText;
	private List<BaseProgressFragment> frags = new ArrayList<BaseProgressFragment>(2);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public int getContentView() {
		return R.layout.act_my_title;
	}

	@Override
	public void initView() {
		//初始化参数
		if (StringUtils.isBlank(name)) {
			name = getIntent().getStringExtra(BUNDLE_KEY_NAME);
		}

//		initStatusBar();

		initToolBar();

		initFromIntent(name, getIntent());

	}

	@Override
	public void initData() {
	}

	private void initStatusBar() {

		//设定状态栏的颜色，当版本大于4.4时起作用
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			// 创建状态栏的管理实例
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			// 激活状态栏设置
			tintManager.setStatusBarTintEnabled(true);
			// 设置一个状态栏资源
			tintManager.setStatusBarTintResource(R.color.bg_status_bar);

		}
	}

	private void initToolBar() {
		mToolbar = (Toolbar) findViewById(R.id.id_common_toolbar);

		//使用自定义标题（不使用默认标题）
		mToolbar.setTitle("");
		leftTitleText = (TextView) mToolbar.findViewById(R.id.id_common_bar_left_title);
		titleText = (TextView) mToolbar.findViewById(R.id.id_common_bar_title);
		
		//使得ToolBar实现
		setSupportActionBar(mToolbar);

		actionBar = getSupportActionBar();

		assert actionBar != null;

		// 给左上角图标的左边加上一个返回的图标 
		actionBar.setDisplayHomeAsUpEnabled(true);
		//自定义后退图标
		mToolbar.setNavigationIcon(R.drawable.sl_common_top_title_back);
		mToolbar.invalidate();
		mToolbar.setNavigationOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				onBackPressed();
			}
		});

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			actionBar.setElevation(25);
		}

	}

	protected void initFromIntent(String name, Intent data) {
		if (data == null)
			throw new RuntimeException("you must provide a page info to display");

		MyPageHelper page = MyPageHelper.getPageByName(name);
		if (page == null)
			throw new IllegalArgumentException("can not find page by value:" + name);

		Bundle args = data.getBundleExtra(BUNDLE_KEY_ARGS);
		if (args != null && args.containsKey(BUNDLE_KEY_TITLE)) {
			setTitle(args.getString(BUNDLE_KEY_TITLE));
		} else
			setTitle(page.getTitle());

		try {
			Fragment fragment = (Fragment) page.getClz().newInstance();

			if (args != null) {
				fragment.setArguments(args);
			}

			FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
			trans.replace(R.id.container, fragment);
			trans.commitAllowingStateLoss();

			mFragment = new WeakReference<Fragment>(fragment);
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException("generate fragment error. by value:" + name);
		}
	}

	/**
	 * 设置标题
	 * @param title
	 */
	public void setTitle(String title) {
		if (titleText != null) {
			titleText.setText(title);
		}
	}

	/**
	 * 设置标题
	 * @param resId
	 */
	public void setTitle(int resId) {
		if (resId != 0) {
			setTitle(getString(resId));
		}
	}

	/**
	 * 中标题
	 * @return
	 */
	public TextView getCustomTitle() {
		return titleText;
	}

	/**
	 * 设置左标题
	 * @param title
	 */
	public void setLeftTitle(String title) {
		if (leftTitleText != null) {
			leftTitleText.setText(title);
			leftTitleText.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 设置左标题
	 * @param resId
	 */
	public void setLeftTitle(int resId) {
		if (resId != 0) {
			setLeftTitle(getString(resId));
		}
	}

	/**
	 * 左标题
	 * @return
	 */
	public TextView getLeftTitle() {
		return leftTitleText;
	}

	@Override
	public void onAttachFragment(Fragment fragment) {
		super.onAttachFragment(fragment);

		//同Fragment通信，接口穿透
		if (fragment instanceof BaseProgressFragment)
			frags.add((BaseProgressFragment) fragment);
		else
			throw new RuntimeException("必需使用BaseProgressFragment做为父类");
	}

	@Override
	public void onBackPressed() {
		for (BaseProgressFragment frag : frags) {
			frag.onBackPressed();
		}
	}

	/**
	 * 监听返回--是否退出程序
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			for (BaseProgressFragment frag : frags) {
				frag.onBackPressed();
			}
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.id_common_bar_back_btn:
			finish();
			break;

		default:
			break;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		for (BaseProgressFragment frag : frags) {
			if (frag.onCreateOptionsMenu(menu)) {//已处理直接返回
				return true;
			}
		}

		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		for (BaseProgressFragment frag : frags) {
			if (frag.onOptionsItemSelected(item)) {//已处理直接返回
				return true;
			}
		}

		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		for (BaseProgressFragment frag : frags) {
			if (frag.isAdded())
				frag.onActivityResult(requestCode, resultCode, data);
		}
	}

	public Toolbar getToolBar() {
		return mToolbar;
	}

}
